package com.vnl.system.aaa.util;

import java.util.Map;


import org.apache.log4j.Logger;
import org.vnl.platform.job.IJob;
import org.vnl.platform.job.JobExecException;

import com.vnl.system.aaa.service.AAAServiceFactory;
import com.vnl.system.aaa.service.IAAService;
import com.vnl.system.aaa.service.ICompanyService;
import com.vnl.system.aaa.service.IEntityCreator;
import com.vnl.system.aaa.service.IRoleService;
import com.vnl.system.aaa.service.ISystemService;
import com.vnl.system.aaa.service.IUserService;

public class AAServiceFactorySetupJob implements IJob {
	private static final Logger logger = Logger.getLogger(AAServiceFactorySetupJob.class);
	
	private static final String AA_SERVICE = "AA_SERVICE";
	private static final String COMPANY_SERVICE = "COMPANY_SERVICE";
	private static final String USER_SERVICE = "USER_SERVICE";
	private static final String ENTITY_CREATOR = "ENTITY_CREATOR";
	private static final String ROLE_SERVICE = "ROLE_SERVICE";
	private static final String SYSTEM_SERVICE = "SYSTEM_SERVICE";
	
	private Map<String, ? extends Object> map;

	@Override
	public int exec() throws JobExecException {
		AAAServiceFactory f = AAAServiceFactory.getInstance();
		Object obj = createObject(map.get(AA_SERVICE), IAAService.class);
		f.setAAservice(obj == null ? null : (IAAService) obj);
		obj = createObject(map.get(COMPANY_SERVICE), ICompanyService.class);
		f.setCompanyService(obj == null ? null : (ICompanyService) obj);
		obj = createObject(map.get(USER_SERVICE), IUserService.class);
		f.setUserService(obj == null ? null : (IUserService) obj);
		obj = createObject(map.get(ENTITY_CREATOR), IEntityCreator.class);
		f.setEntityCreator(obj == null ? null : (IEntityCreator) obj);
		obj = createObject(map.get(ROLE_SERVICE), IRoleService.class);
		f.setRoleService(obj == null ? null : (IRoleService) obj);
		obj = createObject(map.get(SYSTEM_SERVICE), ISystemService.class);
		f.setSystemService(obj == null ? null : (ISystemService) obj);
		// TODO 增加其他Service
		return RESULT_SUCCESS;
	}
	
	

	private Object createObject(Object clzName, Class<?> clz) {
		if (clzName == null) {
			return null;
		}
		try {
			Object obj = Class.forName((String) clzName).newInstance();
			if (clz.isInstance(obj)) {
				return obj;
			}
		} catch (InstantiationException e) {
			logger.error("Cannot create service:"+clz.getName(),e);
		} catch (IllegalAccessException e) {
			logger.error("Cannot create service:"+clz.getName(),e);
		} catch (ClassNotFoundException e) {
			logger.error("Cannot create service:"+clz.getName(),e);
		}
		return null;
	}

	@Override
	public void reset() throws JobExecException {
		AAAServiceFactory.getInstance().clear();
	}

	@Override
	public void setParams(Map<String, ? extends Object> arg0) {
		map = arg0;
	}
	
}
